import React from 'react';
import ReactDom from 'react-dom';
import CreateWkpDialog from './createWorkspaceDialog.jsx';
import Button from 'react-bootstrap/lib/Button';
import HttpRequest from '../HttpRequest.js';
import List from "../component/List.jsx";
import msgFrontAgent from  '../msgFrontAgent.js';
import WorkspaceListNav from './WorkspaceListNav.jsx';
import Modal from "../../../../node_modules/react-bootstrap/lib/Modal";
import Input from '../../../../node_modules/react-bootstrap/lib/Input';
import ListGroup from "react-bootstrap/lib/ListGroup";
import ListGroupItem from "react-bootstrap/lib/ListGroupItem";

let WorkspaceManageTab = React.createClass({
    getInitialState: function () {
        return {
            current_project: this.props.current_project
        };
    },
    componentWillReceiveProps: function (newProps) {
        this.setState({
            current_project: newProps.current_project
        }, this.componentWillMount);
    },
    /**
     * 渲染前的处理
     * 1.获取项目所有工作空间
     * 2.
     */
    componentWillMount: function () {
        this._getWorkspaces();
    },
    componentDidMount: function () {
        var that = this;
        msgFrontAgent.onConnected(function () {
                msgFrontAgent.order('add_workspace', function (data) {
                    that._getWorkspaces();
                });
                msgFrontAgent.order('delete_workspace', function (data) {
                    that._getWorkspaces();
                });
            }
        );
    },
    componentWillUnmount: function () {
        //移除监听删除工作空间的过程
        msgFrontAgent.onConnected(function () {
                msgFrontAgent.disorder('add_workspace');
                msgFrontAgent.disorder('delete_workspace');
            }
        );
    },
    _createWorkspace: function () {
        this.refs.createWkpDialog.handleOpen();
    },
    _getWorkspaces: function () {
        var that = this;
        var project_id = this.state.current_project._id;
        if (project_id) {
            HttpRequest.getWorkspaces(project_id).success(function (res) {
                let workspaces = [];
                res.map(function (item) {
                    item.name = item.work_name;
                    item.type = "workspace";
                    workspaces.push(item);
                });
                that.setState({
                    workspaces: workspaces,
                    List: <List ListData={workspaces}
                                ItemStyle={{cursor: "pointer"}}
                                SelectedItemStyle={{backgroundColor:"#f3f3f3",cursor: "pointer"}}
                                onItemSelected={that.onItemSelected}
                                itemDeleted={that.delete}
                                ifEmpty={<span style={{color:"#969696",paddingLeft:"50px",fontSize:"14px",fontFamily:'Microsoft YaHei'}}>该项目没有工作空间！ </span>}
                                IconMap={[{type:"workspace",icon:<i className="fa fa-cube" style={{fontSize:"20px",cursor:"pointer"}}/>}]}
                    />,
                    current_selected: workspaces[workspaces.length - 1]
                });
            }).error(function (error) {
                console.log('获取工作空间列表失败');
            });
        }
    },
    //_renderWkpList: function () {
    //    this.setState({
    //        List: <List ListData={this.state.workspaces}
    //                    ItemStyle={{cursor: "pointer"}}
    //                    SelectedItemStyle={{backgroundColor:"#f3f3f3",cursor: "pointer"}}
    //                    onItemSelected={this.onItemSelected}
    //                    itemDeleted={this.delete}
    //                    ifEmpty={<span style={{color:"#969696",paddingLeft:"50px",fontSize:"14px",fontFamily:'Microsoft YaHei'}}>该项目没有工作空间！ </span>}
    //                    IconMap={[{type:"workspace",icon:<i className="fa fa-delicious" style={{fontSize:"20px",cursor:"pointer"}}/>}]}
    //        />,
    //        current_selected: this.state.workspaces[this.state.workspaces.length - 1]
    //    });
    //    //if (this.state.workspaces.length > 0) {
    //    //this.setState({
    //    //    current_selected: this.state.workspaces[this.state.workspaces.length - 1]
    //    //})
    //    //}
    //},

    onItemSelected: function (item) {
        this.setState({current_selected: item});
    },
    delete: function (work_id) {
        var that = this;
        confirm("确定要删除工作空间吗？", function () {
            var workspace_info = {
                work_id:work_id,
                namespace:that.state.current_project.namespace,
                project_name:that.state.current_project.name
            };
            HttpRequest.deleteWorkspace(workspace_info).success(function (res) {
                if (res.code == 200) {
                    msgFrontAgent.order(res.data.task_id, function (data) {
                        if (data.err) {
                            toastr.error(null, data.err, {timeOut: 0});
                        } else {
                            that._getWorkspaces();
                            toastr.success(null, data.body.msg);
                        }
                    });
                }
            }).error(function (error) {
                toastr.error(null, "删除工作空间失败", {timeOut: 0});
            });
        })
    },
    render: function () {
        return (
            <div style={{height:"100%"}}>
                <div className="content_pageLeft">
                    <span className="info_title" style={{paddingLeft:"30px"}}>工作空间列表</span>
                    <Button bsStyle="primary"
                            style={{backgroundColor:"#303c40",height: "25px",marginRight: "40px",float:"right",paddingTop: "2px"}}
                            onClick={this._createWorkspace}
                            id="add_member">添加
                    </Button>
                    <CreateWkpDialog ref='createWkpDialog' project={this.state.current_project}/>
                    <div style={{overflowY:"auto",height:"100%",maxHeight:"90%",marginTop:"5px"}}>
                        {
                            this.state.List
                        }
                    </div>
                </div>
                <div className="content_pageRight">
                    <div style={{float:"left",width:"50%",height:"calc(100% - 50px)"}}>
                        <div className="info_title">工作空间成员信息</div>
                        <WorkspaceMember current_wkp={this.state.current_selected}
                                         current_project={this.state.current_project}/>
                    </div>
                    <div style={{marginLeft:"50%",height:"calc(100% - 50px)"}}>
                        <div className="info_title">工作空间依赖信息</div>
                        <WorkDependenciesList current_wkp={this.state.current_selected}/>
                    </div>

                </div>
            </div>
        );
    }
});
let WorkDependenciesList = React.createClass({
    getInitialState: function () {
        return {
            current_wkp: this.props.current_wkp,
            wkp_dependenciesList: <div></div>
        }
    },
    componentWillMount: function () {
        if (this.state.current_wkp) {
            var work_id = this.state.current_wkp._id;
            HttpRequest.getDependencies(work_id).success(function (data) {
                this.setState({
                    work_dependencies: data
                }, this._renderDependenciesList);
            }.bind(this)).error(function (error) {
                console.log('获取版本信息失败');
            });
        }
    },
    componentDidMount: function () {

    },
    componentWillUnmount: function () {

    },
    componentWillReceiveProps: function (newProps) {
        this.setState({
            current_wkp: newProps.current_wkp
        }, this.componentWillMount);
    },
    _renderDependenciesList: function () {
        if (this.state.current_wkp) {
            var work_id = this.state.current_wkp._id;
            HttpRequest.getDependencies(work_id).success(function (data) {
                this.setState({
                    wkp_dependenciesList: <table id="workdenp_table" style={{width: "100%"}}>
                        <tbody>
                        {
                            data.map(function (dependency, i) {

                                if (dependency.flag == "same") {   //和项目依赖相同，正常状态 check-circle
                                    return (
                                        <tr
                                            key={i}
                                            style={{borderBottom: "#C4C4C4 1px solid",height:"65px",fontSize:"15px"}}>
                                            <td style={{paddingTop:"24px"}}>{dependency.goods_title}</td>
                                            <td style={{paddingTop:"24px",paddingLeft:"20px",width:"120px"}}>
                                                已是最新版本
                                            </td>
                                        </tr>
                                    )
                                } else if (dependency.flag == "new") {  //项目中有 工作空间中无 为新增依赖
                                    return (
                                        <tr
                                            key={i}
                                            style={{borderBottom: "#C4C4C4 1px solid",height:"65px",fontSize:"15px"}}>
                                            <td style={{paddingTop:"24px"}}>{dependency.goods_title}</td>
                                            <td style={{paddingTop:"24px",paddingLeft:"20px",width:"120px"}}>
                                                新增依赖
                                            </td>
                                        </tr>
                                    )
                                } else if (dependency.flag == "behind") {  //项目和工作空间中都有 但版本不一样
                                    return (
                                        <tr
                                            key={i}
                                            style={{borderBottom: "#C4C4C4 1px solid",height:"65px",fontSize:"15px"}}>
                                            <td style={{paddingTop:"24px"}}>{dependency.goods_title}</td>
                                            <td style={{paddingTop:"24px",paddingLeft:"20px",width:"120px"}}>
                                                有新版本
                                            </td>
                                        </tr>
                                    )
                                } else if (dependency.flag == "invalid") {  //依赖订阅无效
                                    return (
                                        <tr
                                            key={i}
                                            style={{borderBottom: "#C4C4C4 1px solid",height:"65px",fontSize:"15px"}}>
                                            <td style={{paddingTop:"24px"}}>{dependency.goods_title}</td>
                                            <td style={{paddingTop:"24px",paddingLeft:"20px",width:"120px"}}>
                                                已失效
                                            </td>
                                        </tr>
                                    )
                                } else if (dependency.flag == "unload") {   //未下载
                                    return (
                                        <tr
                                            key={i}
                                            style={{borderBottom: "#C4C4C4 1px solid",height:"65px",fontSize:"15px"}}>
                                            <td style={{paddingTop:"24px"}}>{dependency.goods_title}</td>
                                            <td style={{paddingTop:"24px",paddingLeft:"20px",width:"120px"}}>
                                                未下载
                                            </td>
                                        </tr>
                                    )
                                }

                            })
                        }
                        </tbody>
                    </table>
                });
            }.bind(this)).error(function (error) {
                console.log('获取版本信息失败');
            });
        } else {
            this.setState({
                wkp_dependenciesList: <div></div>
            });
        }
    },
    _updateWorkspace: function () {
        var work_id = this.state.current_wkp._id;
        var options = {
            work_id: work_id
        };
        window.loading();
        HttpRequest.updateWkpDependency(options).success(function (res) {
            if (res.code == 200) {
                toastr.success(null, "正在更新工作空间依赖...");
                //this.componentWillMount();
                window.loading();
                let task_id = res.data.task_id;
                msgFrontAgent.order(task_id, function (data) {
                    if (data.err) {
                        toastr.error(null, data.err, {timeOut: 0});
                    } else {
                        toastr.success(null, data.body.msg);
                        this.componentWillMount();
                    }
                    window.removeLoading();
                }.bind(this));
            }else{
                toastr.error(null,"工作空间依赖更新失败", {timeOut: 0});
            }
            window.removeLoading();
        }.bind(this)).error(function (err) {
            toastr.error(null, "更新失败!");
        });
    },
    render: function () {
        return (
            <div style={{float: "left",width:"80%",height:"100%"}}>
                <div style={{maxHeight:"calc(100% - 50px)", overflowY: "auto"}}>
                    {this.state.wkp_dependenciesList}
                </div>
                <div onClick={this._updateWorkspace}
                     ref="sync_btn"
                     id="sync_btn"
                     style={{marginTop:"15px",padding:"0 10px",height: "35px",cursor: "pointer",fontSize: "13px",backgroundColor: "#394146",textAlign: "center",float: "left"}}>
                    <img src="/res/image/sync_b.png" style={{marginTop:"-2px",lineHeight: "35px"}}/>
                    <span style={{marginLeft:"5px",color:"white",lineHeight: "35px"}}>同步依赖</span>
                </div>
            </div>
        )
    }

});
let WorkspaceMember = React.createClass({
    getInitialState: function () {
        return {
            open: false,
            current_wkp: this.props.current_wkp,
            current_project: this.props.current_project
        }
    },
    componentWillMount: function () {
        this._getProjectMembers();
        this._getWkpMembers();

    },
    componentDidMount: function () {
        //this._getWkpMembers();
    },
    componentWillReceiveProps: function (newProps) {
        if (newProps.current_wkp != this.state.current_wkp) {
            this.setState({
                current_wkp: newProps.current_wkp
            }, this._getWkpMembers);
        }
        if (newProps.current_project != this.state.current_project) {
            this.setState({
                current_project: newProps.current_project
            }, this._getProjectMembers);
        }
    },
    hiddenSelect: function (shortId) {
        setTimeout(function () {
            document.getElementById("member_role_" + shortId).style.display = "inline";
            document.getElementById("edit_member_" + shortId).style.display = "none";
        }, 200);
    },
    editRole: function (item, e) {
        var member_role = document.getElementById("member_role_" + item.shortId);
        var edit_member = document.getElementById("edit_member_" + item.shortId);
        member_role.style.display = "none";
        edit_member.style.display = "inline";
        document.getElementById("edit_select_" + item.shortId).focus();
        e.stopPropagation();
    },
    _renderMemberListItem: function () {
        var MemberListItem = [];
        var that = this;
        var roleStyle = {display: "inline"};
        var editRoleStyle = {display: "none", cursor: "pointer"};
        this.state.wkpMembers.map(function (member) {
            let role = "";
            switch (member.role) {
                case "creator":
                    role = "创建者";
                    break;
                case "administrator":
                    role = "管理员";
                    break;
                case "developer":
                    role = "开发者";
                    break;
                case "observer":
                    role = "观察者";
                    break;
            }
            ;
            let operation = <td style={{paddingTop:"24px",width:"65px"}} id="wkp_member_operation">
                <img src="/res/image/delete.png"
                     id={"delete_" + member.shortId}
                     title="删除"
                     onClick={function(){that.removeMember(member.shortId)}}
                     style={{cursor:"pointer",float:"right",width:"21px",height:"21px"}}/>
                <img src="/res/image/edit.png"
                     id={"edit_" + member.shortId}
                     title="修改权限"
                     onClick={that.editRole.bind(that,member)}
                     style={{marginRight:"20px",cursor:"pointer",float:"right",width:"21px",height:"21px"}}/>
            </td>;
            MemberListItem.push(
                <tr key={member.shortId}
                    style={{borderBottom: "#C4C4C4 1px solid",height:"65px",fontSize:"15px"}}>
                    <td style={{paddingTop:"24px",width:"35%"}}>{member.name}</td>
                    <td style={{paddingTop:"24px",paddingLeft:"20px",width:"120px"}}>
                        <div id={"member_role_"+ member.shortId} style={roleStyle}>{role}</div>
                        <div id={"edit_member_"+member.shortId} style={editRoleStyle}>
                            <select className="edit_member"
                                    onBlur={function(){that.hiddenSelect(member.shortId)}}
                                    style={{background: "#fbfbfb"}}
                                    id={"edit_select_" + member.shortId}
                                    default={member.role}>
                                <option value='administrator'>管理员</option>
                                <option value='developer'>开发者</option>
                                <option value='observer'>观察者</option>
                            </select>
                            <img src='/res/image/save.png' className='edit_member_save'
                                 id={"confirm_edit_" + member.shortId}
                                 onClick={()=>{that.editMember(member.shortId)}}/>
                        </div>
                    </td>
                    {(role != "创建者") ? operation : <td/>}
                </tr>
            );
        });
        this.setState({
            MemberListItem: MemberListItem
        });
    },
    _getWkpMembers: function () {
        var that = this;
        if (that.state.current_wkp) {
            HttpRequest.getWorkspaceById(that.state.current_wkp._id).success(
                function (res) {
                    that.setState({
                        wkpMembers: res.data.user
                    }, that._renderMemberListItem);
                }
            ).error();

        } else {
            that.setState({
                wkpMembers: []
            }, that._renderMemberListItem)
        }
    },
    _getProjectMembers: function () {
        //获取项目所有成员
        var that = this;
        HttpRequest.getMembers(that.state.current_project._id).success(function (msg) {
            if (msg.code == 0) {
                let user_short_ids = [];
                msg.data.map((member)=> {
                    user_short_ids.push(member.user);
                });
                HttpRequest.getMembersByShortIdArr({"shortid": user_short_ids}).success(function (members) {
                    let memberOptions = [];
                    members.data.map(function (member) {
                        memberOptions.push(
                            <option key={member.shortid}
                                    value={JSON.stringify({'shortid':member.shortid,'loginname':member.loginname})}>{member.loginname}</option>
                        );

                    });
                    that.setState({
                        memberOptions: memberOptions
                    });
                });
            }
        });
    },
    _openDialog: function () {
        this.setState({
            open: true
        });
    },
    handleClose: function () {
        this.setState({open: false});
    },
    handleCompleted: function () {
        var wkp_id = this.state.current_wkp._id;
        var user = JSON.parse(this.refs['user'].getValue());
        var shortId = user.shortid;
        var name = user.loginname;
        HttpRequest.addWkpMembers(wkp_id, {
            "role": this.refs['role'].getValue(),
            "name": name,
            "shortId": shortId
        }).success(function (data) {
            if (data.code == 200) {
                if (data.message) {
                    toastr.warning(null, data.message);
                } else {
                    this._getWkpMembers();
                    this.handleClose();
                    toastr.success(null, "工作空间添加成员成功");
                }
            }
        }.bind(this)).error(function (err) {
            toastr.error(null, "工作空间添加成员失败");
        });

    },

    removeMember: function (shortId) {
        confirm("确定将该成员从工作空间中移出吗？", function () {
            var wkp_id = this.state.current_wkp._id;
            HttpRequest.removeWkpMembers(wkp_id, shortId).success(function (data) {
                if (data.code == 200) {
                    if (data.message) {
                        toastr.warning(null, data.message);
                    } else {
                        this._getWkpMembers();
                        toastr.success(null, "从工作空间中移除成员成功");
                    }
                }
            }.bind(this)).error(function (err) {
                toastr.error(null, "从工作空间中移除成员失败");
            });
        }.bind(this));
    },
    editMember: function (shortId) {
        var wkp_id = this.state.current_wkp._id;
        var role = document.getElementById('edit_select_' + shortId).value;
        HttpRequest.editWkpMembers(wkp_id, {shortId: shortId, role: role}).success(function (data) {
            if (data.code == 200) {
                if (data.message) {
                    toastr.warning(null, data.message); //无此成员
                } else {
                    this._getWkpMembers();
                    document.getElementById("member_role_" + shortId).style.display = "inline";
                    document.getElementById("edit_member_" + shortId).style.display = "none";
                    toastr.success(null, "成员编辑成功");
                }
            }
        }.bind(this)).error(function (err) {
            toastr.error(null, "成员编辑失败");
        });
    },

    render: function () {
        return (
            <div style={{width:"80%",height:"100%"}}>
                <div style={{width: "100%",maxHeight:"calc(100% - 50px)", overflowY: "auto"}}>
                    <table id="workMember_table" style={{width: "100%"}}>
                        <tbody >
                        {this.state.MemberListItem}
                        </tbody>
                    </table>
                </div>
                <div style={{marginTop:"5px",width:"300px"}}>
                    <div onClick={this._openDialog}
                         style={{marginTop:"15px",padding:"0 10px",height: "35px",cursor: "pointer",fontSize: "13px",backgroundColor: "#394146",textAlign: "center",float: "left"}}>
                        <img src="/res/image/xinjian.png" style={{marginTop:"-2px",lineHeight: "35px"}}/>
                        <span style={{marginLeft:"5px",color:"white",lineHeight: "35px"}}>添加成员</span>
                    </div>
                </div>
                <Modal
                    show={this.state.open}
                >
                    <Modal.Header>
                        <Modal.Title >添加成员</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <Input type="select" ref="user" label="用户">
                            {this.state.memberOptions}
                        </Input>
                        <Input type="select" ref="role" label="角色">
                            <option value="developer">开发者</option>
                            <option value="administrator">管理员</option>
                            <option value="observer">观察者</option>
                        </Input>
                    </Modal.Body>
                    <Modal.Footer>
                        <Button onClick={this.handleClose}
                                style={{backgroundColor: "#555", borderColor: "#555",width:"70px",margin:'12'}}
                                bsStyle="primary">取消</Button>
                        <Button onClick={this.handleCompleted}
                                style={{backgroundColor: "#555", borderColor: "#555",width:"70px",margin:'12'}}
                                bsStyle="primary">完成</Button>
                    </Modal.Footer>
                </Modal>

            </div>
        )
    }
});

//let addMemberDlg = react.createClass({
//    render: function(){
//        return (
//
//        )
//    }
//});
module.exports = WorkspaceManageTab;